﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[AddComponentMenu("BToolkit/SwitchButtonGroup")]
public class SwitchButtonGroup : MonoBehaviour
{
    public static event Action<SwitchButtonGroup> onGroupInit;
    public int currIndex;
    [Serializable]
    public class ValueEvent : UnityEvent<int> { }
    [Space]
    public ValueEvent onSwitchChange;

    public RectTransform rectTransform { get { return transform as RectTransform; } }

    List<SwitchButton> buttons = new List<SwitchButton>();

    void Awake()
    {
        Init();
    }

    public void Init()
    {
        onGroupInit?.Invoke(this);
    }

    public void _OnAddButton(SwitchButton button)
    {
        if (!buttons.Contains(button))
        {
            buttons.Add(button);
            RefreshButtons();
        }
    }

    public void _OnRemoveButton(SwitchButton button)
    {
        if (buttons.Contains(button))
        {
            buttons.Remove(button);
            RefreshButtons();
        }
    }

    public void _OnSwitchOn(int index)
    {
        this.currIndex = index;
        onSwitchChange?.Invoke(index);
        for (int i = 0; i < buttons.Count; i++)
        {
            SwitchButton button = buttons[i];
            if (button)
            {
                if (button.off) button.off.SetActive(i != index);
                button.on.SetActive(i == index);
            }
        }
    }

    void RefreshButtons()
    {
        for (int i = 0; i < buttons.Count; i++)
        {
            if (!buttons[i]) buttons.RemoveAt(i);
        }
        buttons.Sort((SwitchButton A, SwitchButton B) =>
        {
            return A.rectTransform.GetSiblingIndex() - B.rectTransform.GetSiblingIndex();
        });
        for (int i = 0; i < buttons.Count; i++)
        {
            buttons[i].index = i;
            buttons[i].SetIsOn(i == currIndex, false);
        }
    }
}